package com.dense.kuiniu.floatcabinet.mvp.presenter;

import com.dense.kuiniu.floatcabinet.mvp.contract.QueryContract;
import com.dense.kuiniu.floatcabinet.mvp.event.OpenDoorEvent;
import com.dense.kuiniu.floatcabinet.mvp.http.entity.BaseResponse;
import com.dense.kuiniu.floatcabinet.mvp.http.entity.Book;
import com.dense.kuiniu.floatcabinet.mvp.http.entity.Reader;
import com.dense.kuiniu.floatcabinet.mvp.model.AuthenticationModel;
import com.dense.kuiniu.floatcabinet.mvp.model.QueryModel;
import com.dense.kuiniu.floatcabinet.utils.RxUtils;
import com.jess.arms.integration.EventBusManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.mvp.IModel;

import java.util.List;

import javax.inject.Inject;

import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;

/**
 * @author Administrator
 * @date 2020/11/2
 */
public class QueryPresenter extends BasePresenter<IModel, QueryContract.View> {
    @Inject
    QueryModel userModel;

    @Inject
    AuthenticationModel authenticationModel;

    @Inject
    RxErrorHandler rxErrorHandler;

    @Inject
    public QueryPresenter(QueryContract.View rootView) {
        super(rootView);
    }

    public void query(String key) {
        userModel.query(key)
                .compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<List<Book>>(rxErrorHandler) {
                    @Override
                    public void onNext(List<Book> books) {
                        mRootView.showData(books);
                    }
                });
    }

    public void authentication(Book book, String account) {
        if (account != null && !account.isEmpty()) {
            authenticationModel.readerAuthentication(account, "")
                    .compose(RxUtils.applySchedulers(mRootView))
                    .subscribe(new ErrorHandleSubscriber<BaseResponse<Reader>>(rxErrorHandler) {
                        @Override
                        public void onNext(BaseResponse<Reader> response) {
                            if (response.isSuccess()) {
                                openDoor(account, book.getDoorNumber());
                                mRootView.showInfo("正在开门...");
                            } else {
                                mRootView.showMessage(response.getMsg());
                            }
                        }
                    });
        }
    }

    private void openDoor(String account, int doorNumber) {
        EventBusManager.getInstance().post(new OpenDoorEvent(account, 1, doorNumber));
    }

}